package com.ruoyi.project.mobile.user;

import com.ruoyi.common.utils.*;
import com.ruoyi.project.system.coinrecord.domain.HaoqiCoinRecord;
import com.ruoyi.project.system.coinrecord.service.IHaoqiCoinRecordService;
import com.ruoyi.project.system.member.domain.Member;
import com.ruoyi.project.system.member.enums.MemberExamine;
import com.ruoyi.project.system.member.enums.MemberIsVip;
import com.ruoyi.project.system.member.enums.MemberStatus;
import com.ruoyi.project.system.member.service.IMemberService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Map;

/**
 * 功能：
 *
 * @author：dell
 * @create：2020/6/20 9:50
 * @version：2020 Version：1.0
 * @company：老屋新房 Created with IntelliJ IDEA
 */
@RestController
@RequestMapping("/api")
public class ApiLoginController {

	@Autowired
	private IMemberService memberService;
    @Autowired
    private IHaoqiCoinRecordService haoqiCoinRecordService;

	/**
	 * 小程序登录
	 * @param map
	 * @return
	 */
	@PostMapping("/login")
	@Transactional
	public R findOpenid(@RequestBody Map<String, Object> map){
		JSONObject webAuthorizeInfo = WeixinUtils.getWebAuthorizeInfo((String) map.get("code"));
		String openid = webAuthorizeInfo.getString("openid");
		// 获取会话密钥（session_key）
		String session_key = webAuthorizeInfo.getString("session_key").replace(" ","+");
		//查询数据库是否存在改用户信息
		Member oldMember = this.memberService.findOneByOpenId(openid);
		//如果找不到用户信息 就返回openid
		if(oldMember==null){

			try {
				String decrypts = AesCbcUtil.decrypt(map.get("encryptedData").toString(), session_key,map.get("iv").toString(), "UTF-8");


				if (null != decrypts && decrypts.length() > 0) {
					JSONObject jsons = new JSONObject(decrypts);
					System.out.println("jsons:: "+jsons.toString());
                    /*String gender = jsons.get("gender").toString();
                    MemberUser.setCityId(jsons.get("city").toString()); // 城市
                    MemberUser.setProvinceId(jsons.get("province").toString());// 省份*/
                    Member member = new Member();
					member.setUsername(jsons.get("nickName").toString());
					member.setSex((Integer) jsons.get("gender"));
					member.setOpenid(openid);
					member.setHeadpic(jsons.get("avatarUrl").toString());
					member.setStatus(MemberStatus.NORMAL.getValue());
					member.setRecommendNum(0L);

                    //  设置新人积分500分、关联微信号30分
					member.setHaoqiCoin(new BigDecimal(530));
					//  设置历史总积分
                    member.setHistoryTotalCoin(new BigDecimal(530));

					member.setIsExamine(MemberExamine.INCOMPLETE.getValue());
					member.setIsVip(MemberIsVip.NO.getValue());
					member.setRole(1);
					member.setCreated(DateUtils.getNowDate());
					member.setIsNew(0);
					member.setCoin(new BigDecimal(0));

					if (map.containsKey("introUser")&&!StringUtils.isBlank(map.get("introUser").toString())){
						member.setIntroUser(map.get("introUser").toString());
						//修改推荐人的推荐数量
						Member oldIntro = this.memberService.selectMemberById(member.getIntroUser());
						Member intro = new Member();
						intro.setId(member.getIntroUser());
						intro.setRecommendNum(oldIntro.getRecommendNum()+1);
						this.memberService.updateMember(intro);
					}
					this.memberService.insertMember(member);

					//新人积分增加成功进行积分反馈
					HaoqiCoinRecord rookiePointsCoinRecord = new HaoqiCoinRecord();
					rookiePointsCoinRecord.setStatus(1);
					rookiePointsCoinRecord.setMemberId(member.getId());
					rookiePointsCoinRecord.setType(2);
					rookiePointsCoinRecord.setGetType(1);
					rookiePointsCoinRecord.setCreated(DateUtils.getNowDate());
					rookiePointsCoinRecord.setNum(new BigDecimal(500));
					rookiePointsCoinRecord.setResId(member.getId());
					this.haoqiCoinRecordService.insertHaoqiCoinRecord(rookiePointsCoinRecord);
					//关联微信号积分增加成功进行积分反馈
					rookiePointsCoinRecord.setStatus(1);
					rookiePointsCoinRecord.setMemberId(member.getId());
					rookiePointsCoinRecord.setType(2);
					rookiePointsCoinRecord.setGetType(6);
					rookiePointsCoinRecord.setCreated(DateUtils.getNowDate());
					rookiePointsCoinRecord.setNum(new BigDecimal(30));
					rookiePointsCoinRecord.setResId(member.getId());
					this.haoqiCoinRecordService.insertHaoqiCoinRecord(rookiePointsCoinRecord);
					return RFactory.generateR(member);
				} else {
					return R.error("授权失败");
				}

			} catch (Exception e) {
				e.printStackTrace();
			}


			return RFactory.generateR(webAuthorizeInfo.toString());
		}
		//判断用户是否被禁用
		if(oldMember.getStatus().equals(MemberStatus.DISABLE.getValue())){
			return R.error("账户被禁用,请联系管理员");
		}

		return RFactory.generateR(oldMember);
	}



	/**
	 * 绑定手机号
	 * @param map
	 * @return
	 */
	@PostMapping("/mobile")
	@Transactional
	public R updateMobile(@RequestBody Map<String, Object> map){
		JSONObject webAuthorizeInfo = WeixinUtils.getWebAuthorizeInfo((String) map.get("code"));
		String openid = webAuthorizeInfo.getString("openid");
		// 获取会话密钥（session_key）
		String session_key = webAuthorizeInfo.getString("session_key").replace(" ","+");
		//查询数据库是否存在改用户信息
		Member oldMember = this.memberService.findOneByOpenId(openid);
		if(oldMember==null){
			return R.error("请先授权头像昵称");
		}
		try {
			String decrypts = AesCbcUtil.decrypt(map.get("encryptedData").toString(), session_key,map.get("iv").toString(), "UTF-8");
			if (null != decrypts && decrypts.length() > 0) {

				JSONObject jsons = new JSONObject(decrypts);
				System.out.println("jsons:: "+jsons.toString());
				//更新手机号
				Member member = new Member();
				member.setMobile(jsons.get("purePhoneNumber").toString());
				member.setId(oldMember.getId());
				this.memberService.updateMember(member);
			}else{
				return R.error("授权失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return R.ok();
	}

	/**
	 * 小程序注册
	 * @param member
	 * @return
	 */
	@PostMapping("/register")
	@Transactional
	public R addMember(@RequestBody Member member){
		//判断用户是否已经注册
		Member oldMember = this.memberService.findOneByOpenId(member.getOpenid());
		if(oldMember!=null){
			return RFactory.generateR(oldMember);
		}
		//添加用户信息
		member.setStatus(MemberStatus.NORMAL.getValue());
		member.setRecommendNum(0L);
		member.setHaoqiCoin(new BigDecimal(0));
		member.setIsExamine(MemberExamine.INCOMPLETE.getValue());
		member.setIsVip(MemberIsVip.NO.getValue());
		member.setRole(1);
		member.setCreated(DateUtils.getNowDate());
		this.memberService.insertMember(member);
		//如果存在推荐人 则找到推荐人 并修改信息
		if(!StringUtils.isBlank(member.getIntroUser())){
			Member intro = this.memberService.selectMemberById(member.getIntroUser());
			if(intro!=null){
				Member update = new Member();
				update.setId(member.getIntroUser());
				update.setRecommendNum(intro.getRecommendNum()+1);
				this.memberService.updateMember(update);
			}
		}
		return RFactory.generateR(member);
	}

}
